﻿#$language = "Python"
#$interface = "1.0"

import os
import sys
import subprocess
import _subprocess

g_local_path = os.path.dirname(os.path.abspath(__file__))
if g_local_path not in sys.path:
    sys.path.insert(0, g_local_path)

import debug

FORMAT_XML_TOOL = 'D:\\Local_R\\macro\\tools\\FormatXML.exe'
LOCAL_PLAN_PATH = 'D:\\_logs\\Upload_plan'

def hide_window():
    hide_info = subprocess.STARTUPINFO()
    hide_info.dwFlags = _subprocess.CREATE_NEW_CONSOLE | \
                        _subprocess.STARTF_USESHOWWINDOW
    hide_info.wShowWindow = _subprocess.SW_HIDE
    return hide_info

def format_xml(xml_file_name):
    log = debug.Log()
    if not os.path.isfile(FORMAT_XML_TOOL):
        log.w('Format xml tool"' + FORMAT_XML_TOOL + '" does not exist.')
        return False

    args = FORMAT_XML_TOOL + ' ' + xml_file_name
    log.w('Format xml ' + xml_file_name, end=' ')

    # set cwd for format xml tool will backup xml file in working directory
    proc = subprocess.Popen(args,  
                            shell=False, 
                            stdout=subprocess.PIPE, 
                            cwd=os.path.dirname(FORMAT_XML_TOOL), 
                            startupinfo=hide_window())

    format_rslt = False
    rslt_msg = 'failed.'
    fail_msg = None
    std_out, std_err = proc.communicate()
    for line in std_out.splitlines():
        if 'Succeed' in line:
            format_rslt = True
            rslt_msg = 'successful.'
            break
        elif 'Sorry' in line:
            fail_msg = line
            break

    log.w(rslt_msg, False)
    if fail_msg is not None:
        log.w(fail_msg)

    del log
    return format_rslt
